import { useState, useEffect, useRef } from "react";
import { Button, Popover, Popconfirm, message, Modal } from "antd";
import moment from "moment";
import IconFont from "@/components/IconFont";
import CommonTable from "@/components/CommonTable";
import CommonPagination from "@/components/CommonPagination";
import CommonLoading from "@/components/CommonLoading";
import {
	queryWaitCreateCombinationList,
	waitCreateCombinationIds,
	createCombinationSku,
	deleteCombinationSku
} from "../../../service";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { isEmpty } from "lodash";
import ResultModal from "./ResultModal";
import { isJSON } from "@/utils/utils.jsx";

const initPagination = {
	current: 1,
	total: 0,
	pageSize: 100,
	showQuickJumper: true,
	pageSizeOptions: [10, 20, 50, 100, 500]
};

const dateFormat = "YYYY-MM-DD HH:mm:ss";

const TableList = ({ query, divEl }) => {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState([]);
	const [pagination, setPagination] = useState(null); //分页数据
	const [selectRowKeys, setSelectRowKeys] = useState([]);
	const [visible, setVisible] = useState(false);
	const [resultData, setResultData] = useState({}); //创建结果

	const stageParams = useRef({});

	const columns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			fixed: "left",
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "图片",
			dataIndex: "combinationGoodsImage",
			key: "combinationGoodsImage",
			width: 120,
			render: text => (
				<div>
					{text ? (
						<Popover content={<img src={text} style={{ width: 400 }} />}>
							<img src={text} style={{ width: "32px", height: "32px", borderRadius: "5px" }} />
						</Popover>
					) : (
						""
					)}
				</div>
			)
		},
		{
			title: "组合装名称",
			dataIndex: "combinationGoodsName",
			key: "combinationGoodsName",
			width: 120
		},
		{
			title: "组合编号",
			dataIndex: "combinationGoodsCode",
			key: "combinationGoodsCode",
			width: 120
		},
		{
			title: "零售价（元）",
			dataIndex: "retailPrice",
			key: "retailPrice",
			width: 120
		},
		{
			title: "已解析系统商品编码",
			dataIndex: "containSysGoodsCode",
			key: "containSysGoodsCode",
			width: 160,
			render: text => {
				return (
					<div>
						{isJSON(text)
							? JSON.parse(text).map(item => (
									<span>
										<span>{item.skuCode}</span>
										<span>（{item.num}）</span>
									</span>
								))
							: ""}
					</div>
				);
			}
		},
		{
			title: "缺失系统商品编码",
			dataIndex: "deletionSysGoodsCode",
			key: "deletionSysGoodsCode",
			width: 150,
			render: text => {
				return (
					<div>
						{isJSON(text)
							? JSON.parse(text).map(item => (
									<span>
										<span className="common-color9">{item.skuCode}</span>
										<span>（{item.num}）</span>
									</span>
								))
							: ""}
					</div>
				);
			}
		},
		{
			title: "生成时间",
			dataIndex: "createTime",
			key: "createTime",
			width: 95,
			render: text => moment(text).format("YYYY-MM-DD HH:mm:ss")
		},
		{
			title: "操作",
			key: "id",
			dataIndex: "id",
			width: 150,
			fixed: "right",
			render: (_, record) => (
				<div className="opera-span-common" style={{ display: "felx", alignItems: "center" }}>
					<>
						<Button type="link" onClick={() => handleCreate(record)} key="6">
							确认创建
						</Button>
					</>
					<Button type="link" onClick={() => handleDelete(record)}>
						删除
					</Button>
				</div>
			)
		}
	];

	useEffect(() => {
		setPagination({
			...(pagination || initPagination),
			current: 1
		});
	}, [query]);

	useEffect(() => {
		if (pagination) {
			getTableListFunc();
		}
	}, [pagination]);

	//获取列表数据
	const getTableListFunc = async () => {
		setLoading(true);
		setData([]);
		setSelectRowKeys([]);
		const params = {
			...query,
			size: pagination.pageSize,
			current: pagination.current
		};
		if (params.time) {
			params.startTime = moment(params.time[0]._d).format(dateFormat);
			params.endTime = moment(params.time[1]._d).format(dateFormat);
		}
		params.time = undefined;
		stageParams.current = params;
		const { data, success } = await queryWaitCreateCombinationList(params);
		if (success) {
			const { records = [], total = 0 } = data || {};
			pagination.total = total;
			setData(records);
		}
		setLoading(false);
	};

	//根据筛选条件，获取所有待生成组合商品ids
	const getAllIds = async code => {
		setLoading(true);
		const params = {
			...query
		};
		if (params.time) {
			params.startTime = moment(params.time[0]._d).format(dateFormat);
			params.endTime = moment(params.time[1]._d).format(dateFormat);
		}
		params.time = undefined;
		const { success, data = [] } = await waitCreateCombinationIds(params);
		if (success) {
			if (code == "del") {
				handleDeleteConfirm(data);
			} else {
				handleCreateConfirm(data);
			}
		}
		setLoading(false);
	};

	//创建待生成组合商品创建
	const handleCreateConfirm = async ids => {
		setLoading(true);
		const { data = {}, success, msg ='' } = await createCombinationSku({ ids });
		if (success) {
            const { failCount } = data;
            if(failCount > 0) {
                setVisible(true);
            } else {
                message.success(msg);
            }
			setResultData(data);
			setPagination({
				...(pagination || initPagination),
				current: 1
			});
		}
		setLoading(false);
	};

	//点击单个创建
	const handleCreate = record => {
		Modal.confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "创建的组合装将与您的店铺商品执行绑定关系，是否当前的组合装？",
			zIndex: "1100",
			onOk() {
				handleCreateConfirm([record.id]);
			}
		});
	};

	//点击单个删除
	const handleDelete = record => {
		Modal.confirm({
			title: "提示",
			icon: <ExclamationCircleOutlined />,
			content: "是否删除当前的组合装？删除后您的店铺商品可能将没有绑定的系统商品/组合装，请谨慎操作",
			zIndex: "1100",
			onOk() {
				handleDeleteConfirm([record.id]);
			}
		});
	};

	//删除确定
	const handleDeleteConfirm = async ids => {
		setLoading(true);
		const { data, success, msg } = await deleteCombinationSku({ ids });
		if (success) {
			message.success(msg);
			getTableListFunc();
		}
		setLoading(false);
	};

	//批量操作
	const batchHandleOperate = code => {
		// setVisible(true);
		if (data.length) {
			if (selectRowKeys.length) {
				// 勾选
				Modal.confirm({
					title: "提示",
					icon: <ExclamationCircleOutlined />,
					content:
						code == "del"
							? "是否批量删除所勾选的组合装？删除后您的店铺商品可能将没有绑定的系统商品/组合装，请谨慎操作"
							: "创建的组合装将与您的店铺商品执行绑定关系，是否批量创建所勾选的组合装？",
					zIndex: "1100",
					onOk() {
						if (code == "del") {
							//删除
							handleDeleteConfirm(selectRowKeys);
						} else {
							//创建
							handleCreateConfirm(selectRowKeys);
						}
					}
				});
			} else {
				//筛选
				if (!isEmpty(query)) {
					Modal.confirm({
						title: "提示",
						icon: <ExclamationCircleOutlined />,
						content:
							code == "del"
								? "是否批量删除所筛选的组合装？删除后您的店铺商品可能将没有绑定的系统商品/组合装，请谨慎操作"
								: "创建的组合装将与您的店铺商品执行绑定关系，是否批量创建所筛选的组合装？",
						zIndex: "1100",
						onOk() {
							getAllIds(code);
						}
					});
				} else {
					message.info("请先筛选或勾选组合装数据");
				}
			}
		} else {
			message.info("请先筛选或勾选组合装数据");
		}
	};

	//表格滚动高度
	const [scrollHeight, setScrollHeight] = useState(580);

	//监听窗口尺寸变化计算一下高度
	useEffect(() => {
		window.addEventListener("resize", () => {
			handleSetHeight();
		});
		return () => {
			window.removeEventListener("resize", () => {
				handleSetHeight();
			});
		};
	}, []);

	useEffect(() => {
		handleSetHeight();
	}, []);

	//计算表格的滚动高度
	const handleSetHeight = () => {
		try {
			const sumHeight = document.getElementById("sectionContent").clientHeight;
			const searchHeight = divEl && divEl.current ? divEl.current.clientHeight : 0;
			const finalHeight = sumHeight - (searchHeight + 170);
			setScrollHeight(finalHeight);
		} catch (e) {
			console.log(e);
		}
	};

	//表格
	const tableProps = {
		data,
		columns,
		handleRowKey(record) {
			return record.id;
		},
		scroll: { y: scrollHeight },
		rowSelection: {
			type: "checkbox",
			fixed: true,
			selectedRowKeys: selectRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				setSelectRowKeys(selectedRowKeys);
			}
		}
	};

	//分页
	const pageProps = {
		pagination,
		handleChange(current, size) {
			setPagination({
				...pagination,
				current: current == pagination.current ? 1 : current,
				pageSize: size
			});
		}
	};

	//处理结果
	const ResultModalProps = {
		data: resultData,
		handleCancel() {
			setVisible(false);
		},
		handleOk(arr) {
			handleDeleteConfirm(arr);
		}
	};

	return (
		<>
			<div style={{ display: "flex", marginBottom: "16px" }}>
				<Button onClick={() => batchHandleOperate("create")} size="middle" style={{ marginRight: "16px" }} type="primary">
					批量确认创建
				</Button>
				<Button onClick={() => batchHandleOperate("del")} size="middle">
					删除
				</Button>
			</div>
			<CommonTable {...tableProps} />
			<div style={{ marginTop: 8 }}>
				<CommonPagination {...pageProps} />
			</div>
			{visible && <ResultModal {...ResultModalProps} />}
			<CommonLoading loading={loading} />
		</>
	);
};

export default TableList;
